package logic

import (
	"context"
	"encoding/json"
	"strconv"
	"time"
	"zhihu/mobels/cache"
	"zhihu/mobels/mysql"

	"zhihu/zhihurpc/internal/svc"
	"zhihu/zhihurpc/zhihurpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListProblemLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListProblemLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListProblemLogic {
	return &ListProblemLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListProblemLogic) ListProblem(in *zhihurpc.ListProblemRequest) (*zhihurpc.ListProblemResponse, error) {
	// todo: add your logic here and delete this line
	var problem []mysql.Problem
	var problemList []*zhihurpc.ListProblem
	page, _ := strconv.Atoi(in.Page)
	if page <= 0 {
		page = 1
	}

	pageSize, _ := strconv.Atoi(in.PageSize)
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize

	get := cache.Rdb.Get(l.ctx, "problemList"+in.Page+in.PageSize)
	if get.Val() != "" {
		json.Unmarshal([]byte(get.Val()), &problemList)
	} else {
		mysql.DB.Offset(offset).Limit(pageSize).Find(&problem)
		marshal, _ := json.Marshal(&problemList)

		cache.Rdb.Set(l.ctx, "problemList"+in.Page+in.PageSize, marshal, time.Minute*30)
	}

	for _, m := range problem {
		list := zhihurpc.ListProblem{
			Title:     m.Title,
			Content:   m.Content,
			ProblemId: int64(m.ID),
		}
		problemList = append(problemList, &list)
	}

	return &zhihurpc.ListProblemResponse{}, nil
}
